package com.ywxx.dyhelper.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ywxx.dyhelper.BuildConfig;
import com.ywxx.dyhelper.R;
import com.ywxx.dyhelper.model.DYConfig;
import com.ywxx.dyhelper.model.TaskConfig;
import com.ywxx.dyhelper.utils.ConstValues;
import com.ywxx.dyhelper.utils.DYVersionUtils;
import com.ywxx.dyhelper.utils.DateUtils;
import com.ywxx.dyhelper.utils.SqliteDBAcces;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;

import androidx.annotation.RequiresApi;


/**
 * 任务辅助服务
 */
public class TaskService extends AccessibilityService {
    private static final String TAG = "任务点击服务";

    private static TaskService mService;

    private boolean isRunningInFront = false;

    private ShowTypeReceiver receiver;
    private int tasktype = 0;
    private String taskname = "";

    //是否启动工作
    private boolean isWork = false;

    //是否为首页
    private boolean isMain = true;

    private int Max_y = 0;

    //执行的任务栈
    private ArrayList<String> stack_task = new ArrayList<>();


    //随机数
    ThreadLocalRandom random = ThreadLocalRandom.current();

    //ID配置
    private DYConfig config;
    //任务配置
    private TaskConfig taskconfig;

    //是否在聊天界面
    private boolean isChtRoom = false;

    //滑动手势范围
    int width = ConstValues.Screen_Width / 2;
    int start_y = ConstValues.Screen_Height - ConstValues.Screen_Height / 4;
    int end_y = ConstValues.Screen_Height / 4;

    //取消关注使用
    private int needcount = 0;
    private int opercount = 0;
    //观看视频个数
    private int vlog_count = 0;

    private long startTaskTime = 0;
    private long endTaskTime = 0;

    //点赞
    private int like_x = 0;
    private int like_y = 0;
    //关注
    private int follow_x = 0;
    private int follow_y = 0;

    SqliteDBAcces DBAccess;

    DecimalFormat df = new DecimalFormat("#.##");

    //FollowRelationTabActivity 关注窗口
    //UserProfileActivity  用户窗口

    /**
     * 启动服务监听
     */
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();

        mService = this;
        Log.e(TAG, "授权成功...");
        if (receiver != null) {
            unregisterReceiver(receiver);
        }


        receiver = new ShowTypeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstValues.StartTaskAction);
        registerReceiver(receiver, intentFilter);
        SQLiteDatabase db = openOrCreateDatabase(ConstValues.DBFilePath, Context.MODE_PRIVATE, null);
        if (db == null) {
            Log.e(TAG, "数据库异常");
        }

        if (db != null) {
            DBAccess = new SqliteDBAcces(db);
            DBAccess.CreateAutoAdv();
        }
    }

    /**
     * 监听窗口变化
     *
     * @param event
     */
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event == null)
            return;

        //接收事件,如触发了通知栏变化、界面变化等  ds_
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && event.getPackageName().equals("com.ss.android.ugc.aweme")) {
            if (follow_y == 0 || like_x == 0)
                getbtnconfig();
            Log.e(TAG, "窗口变化" + event.getClassName());
            isMain = event.getClassName().toString().contains("MainActivity");
            isChtRoom = event.getClassName().toString().contains(".chat.ChatRoomActivity");

            if (windowManager == null) {
                showFloatingWindow();
            }

        }

//        if (event.getWindowChanges() == AccessibilityEvent.WINDOWS_CHANGE_ACTIVE)
//        Log.e(TAG, "窗口变化" + event.getWindowChanges());
        isRunningInFront = event.getPackageName().equals("com.ss.android.ugc.aweme");
    }

    /**
     * 系统中断辅助服务
     */
    @Override
    public void onInterrupt() {
        isWork = false;
        windowManager = null;
        floatview = null;
        mService = null;
    }

    /**
     * 辅助功能是否启动
     */
    public static boolean isStart() {
        if (mService == null) {
            return false;
        }
        AccessibilityManager accessibilityManager = (AccessibilityManager) mService.getSystemService(Context.ACCESSIBILITY_SERVICE);
        AccessibilityServiceInfo info = mService.getServiceInfo();
        if (info == null) {
            return false;
        }
        List<AccessibilityServiceInfo> list = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        Iterator<AccessibilityServiceInfo> iterator = list.iterator();

        boolean isConnect = false;
        while (iterator.hasNext()) {
            AccessibilityServiceInfo i = iterator.next();
            if (i.getId().equals(info.getId())) {
                isConnect = true;
                break;
            }
        }
        if (!isConnect) {
            return false;
        }

        return true;
    }

    /**
     * 长距离滑动
     */
    private void UpLongGesture() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            int h = (int) (ConstValues.Screen_Height / 5);
            Path path = new Path();
            path.moveTo(width, ConstValues.Screen_Height - h);
            path.lineTo(width, h);

            dispatchGestureMove(path, 200);
        } else {
            //7.0以下手机root可以发送滑动指令
        }
    }

    private void UpGesture() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Path path = new Path();
            path.moveTo(width, start_y);
            path.lineTo(width, end_y);

            dispatchGestureMove(path, 200);
        } else {
            //7.0以下手机root可以发送滑动指令
        }
    }

    private void DownGesture() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Path path = new Path();
            path.moveTo(width, start_y);
            path.lineTo(width, end_y);

            dispatchGestureMove(path, 200);
        } else {
            //7.0以下手机root可以发送滑动指令
        }
    }

    /**
     * 立即发送移动的手势
     * 注意7.0以上的手机才有此方法，请确保运行在7.0手机上
     *
     * @param path  移动路径
     * @param mills 持续总时间
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void dispatchGestureMove(Path path, long mills) {
        if (!isRunningInFront)
            return;
        dispatchGesture(new GestureDescription.Builder().addStroke(new GestureDescription.StrokeDescription
                (path, 0, mills)).build(), null, null);
        isRunningInFront = false;
    }

    /**
     * 点击指定位置
     * 注意7.0以上的手机才有此方法，请确保运行在7.0手机上
     */
    @RequiresApi(24)
    public void dispatchGestureClick(int x, int y) {
        if (!isRunningInFront)
            return;

        if (x < 1 || y < 1)
            return;

        Log.e(TAG, "点击屏幕" + x + "--" + y);

        Path path = new Path();
        path.moveTo(x - 1, y - 1);
        path.lineTo(x + 1, y + 1);
        dispatchGesture(new GestureDescription.Builder().addStroke(new GestureDescription.StrokeDescription
                (path, 0, 100)).build(), null, null);
    }

    /**
     * 长按指定位置
     * 注意7.0以上的手机才有此方法，请确保运行在7.0手机上
     */
    @RequiresApi(24)
    public void dispatchGestureLongClick(int x, int y) {
        if (!isRunningInFront)
            return;
        Path path = new Path();
        path.moveTo(x - 1, y - 1);
        path.lineTo(x, y - 1);
        path.lineTo(x, y);
        path.lineTo(x - 1, y);
        dispatchGesture(new GestureDescription.Builder().addStroke(new GestureDescription.StrokeDescription
                (path, 0, 1000)).build(), null, null);
    }

    /**
     * 获取当前播放类别的标题 推荐列表使用
     *
     * @return
     */
    private String getTitle() {
        List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/title");
        if (nodes.isEmpty() == false) {
            return nodes.get(0).getText().toString();
        }

        return "";
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mService = null;
//        try
//        {
//            unregisterReceiver(receiver);
//
//        } catch (Exception e)
//        {
//
//        }
    }

    /**
     * 类型切换广播
     */
    class ShowTypeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            tasktype = intent.getIntExtra("TaskType", 0);
            taskname = intent.getStringExtra("TaskName");
            taskconfig = (TaskConfig) intent.getSerializableExtra("TaskConfig");
            String dyver = ConstValues.getDyAPPVer(TaskService.this);
            config = DYVersionUtils.getTypeConfig(tasktype, dyver);

            Max_y = ConstValues.Screen_Height - (int) (ConstValues.Density * 65);
            vlog_count = 0;
            startTaskTime = 0;

            mTask.clear();
            handler.sendEmptyMessage(0);
            if (tasktype > 3) {
                opercount = 0;
                needcount = taskconfig.runtime;
            }

            showFloatingWindow();
        }
    }


    private Thread workThread;

    /**
     * 开始执行任务
     */
    private void execTask() {
        if (isWork == true) {
            workThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isWork == true) {
                        if (isRunningInFront == false) {
                            SystemClock.sleep(200);
                            continue;
                        }

                        switch (tasktype) {
                            case 1:
                                //养号模式
                                KeepLive();
                                break;
                            case 2:
                                //万能引流
                                CommonGuide();
                                break;
                            case 3:
                                if (BuildConfig.dz_power.equals("120") && BuildConfig.DEBUG == false)
                                    break;
                                //精准引流
                                AccurateGuide();
                                break;
                            case 4:
                            case 5:
                            case 6:

                                String opertext = "";
                                String opertext1 = "";
                                if (tasktype == 4) {
                                    opertext = taskconfig.auto_follow ? "已关注" : "";
                                    opertext1 = taskconfig.auto_like ? "互相关注" : "";
                                }
                                if (tasktype == 5)
                                    opertext = "关注";
                                if (tasktype == 6)
                                    opertext = "回关";

                                //一键取关
                                if (opercount < needcount) {
                                    CancelFollow(opertext, opertext1);
                                } else {
                                    mTask.add("取关任务完成");
                                    handler.sendEmptyMessage(0);
                                    isWork = false;
                                }
                                break;

                            case 7:

                                if (BuildConfig.dz_power.equals("100") && BuildConfig.DEBUG == false)
                                    break;
                                //自动广告
                                if (opercount < needcount) {
                                    AutoAdvertiseme(taskconfig.sayhello, taskconfig.sendmessage, taskconfig.sendemot);
                                } else {
                                    mTask.add("自动广告任务完成");
                                    handler.sendEmptyMessage(0);
                                    isWork = false;
                                }
                                break;

                            case 8:
                                //一键识别
                                if (opercount < needcount) {
                                    Recognition();
                                } else {
                                    mTask.add("一键识别任务完成");
                                    handler.sendEmptyMessage(0);
                                    isWork = false;
                                }
                                break;
                            case 9:
                                //一键已读
                                AutoReadMessage();
                                break;
                        }
                    }

                    iv_start.setImageResource(isWork ? R.drawable.pause : R.drawable.start);
                }
            });
            workThread.start();
        }
    }


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 0) {
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                    lv.setSelection(mTask.size());
                }
            } else {
                double time = (endTaskTime - System.currentTimeMillis()) / 1000 / 3600d;
                labhead.setText(taskname + ":剩" + df.format(time) + taskconfig.unit + "\r\n设备:" + Build.MODEL);
            }
            return false;
        }
    });

    private void showtaskmsg(String msg) {
        mTask.add(msg);
        handler.sendEmptyMessage(0);
    }

    private void showtasktime() {
        handler.sendEmptyMessage(1);
    }


    /**
     * 养号模式
     */
    private void KeepLive() {
        UpGesture();
        vlog_count++;

        SystemClock.sleep(100);
        //检查是否为广告
        if (CheckAdv() == true) {
            return;
        }
        int time = random.nextInt(5000, 30000);

        showtaskmsg("观看视频:" + df.format(time / 1000d) + "秒");


        if (vlog_count == needcount || needcount == 0) {
            if (needcount > 2) {
                SystemClock.sleep(random.nextInt(100, 500));
                onClickLove(getRootInActiveWindow());
                showtaskmsg("视频执行点赞");
            }
            //下次点赞时间
            needcount = vlog_count + (taskconfig.oprtime == 5 ? 5 : random.nextInt(5, taskconfig.oprtime));
        }

        SystemClock.sleep(time);

        showtasktime();
        //检查执行完成时间
        if (endTaskTime - System.currentTimeMillis() <= 0) {
            showtaskmsg(taskname + "执行完毕");
            isWork = false;
        }
    }

    /**
     * 万能引流
     */
    private void CommonGuide() {

        UpGesture();

        int time = random.nextInt(5000, taskconfig.oprtime);
        //判断是否关注
        int othertime = taskconfig.oprtime * 2;
        int followtime = random.nextInt(500, othertime);
        int liketime = random.nextInt(1000, othertime);
        showtaskmsg("视频观看:" + df.format(time / 1000d) + "秒");

        //检查是否为广告
        if (CheckAdv() == true) {
            SystemClock.sleep(random.nextInt(500, 3000));
            return;
        }


        //不能间隔时间太近
        if (followtime > 0 && liketime > 0 && Math.abs(followtime - liketime) < 200)
            liketime += 200;

        //判断是否点赞
        boolean excefollow = taskconfig.auto_follow == true && followtime < time;
        boolean excelike = taskconfig.auto_like == true && liketime < time;

        //检查是否直播界面 不操作
        if (isMain && CheckOnLone()) {
            excefollow = false;
            excelike = false;
        }

        if (excefollow)
            showtaskmsg("本视频执行关注");
        if (excelike)
            showtaskmsg("本视频执行点赞");

        //如果是首页推荐的话
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null)
            return;

        //点赞关注助手
        while (time > 0) {
            SystemClock.sleep(200);

            if (excefollow == true && time - followtime < 200) {
                if (follow_x == 0 || follow_y == 0) {
                    List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_a);
                    if (list.isEmpty() == false) {
                        int h = ConstValues.Screen_Height / 4;
                        for (AccessibilityNodeInfo info : list) {
                            Rect rect = new Rect();
                            info.getBoundsInScreen(rect);
                            if (rect.top > h && rect.top < ConstValues.Screen_Height) {
                                OnViewClick(info);
                                SystemClock.sleep(200);
                            }
                        }
                    }
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Log.e(TAG, "点击关注按钮：x" + follow_x + " y:" + follow_y);
                        dispatchGestureClick(follow_x, follow_y + 30);
                    }
                }
                excefollow = false;
            }

            if (excelike == true && time - liketime < 200) {
                onClickLove(nodeInfo);
                excelike = false;
            }

            time -= 200;
        }

        showtasktime();
        //检查执行完成时间
        if (endTaskTime - System.currentTimeMillis() <= 0) {
            showtaskmsg(taskname + "执行完毕");
            handler.sendEmptyMessage(0);
            isWork = false;
        }
    }

    /**
     * 执行点赞操作
     *
     * @param root
     */
    private void onClickLove(AccessibilityNodeInfo root) {
        if (isMain == true) {
            List<AccessibilityNodeInfo> list = root.findAccessibilityNodeInfosByViewId(config.id_b);
            if (list.isEmpty() == false) {
                int h = ConstValues.Screen_Height / 4;
                for (AccessibilityNodeInfo info : list) {
                    Rect rect = new Rect();
                    info.getBoundsInScreen(rect);
                    if (rect.top > h && rect.top < ConstValues.Screen_Height) {
                        String desc = (String) info.getContentDescription();
                        boolean isDianzan = TextUtils.isEmpty(desc) || desc.contains("已选中") == false;
                        if (isDianzan) {
                            if (like_y > 0) {
                                like_x = rect.right + (rect.left - rect.right) / 2;
                                like_y = rect.bottom + (rect.top - rect.bottom) / 2;
                            }

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                dispatchGestureClick(like_x, like_y);
                            }
                            SystemClock.sleep(200);
                            Log.i(TAG, "执行了一次点赞操作");
                        }
                    }
                }
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                dispatchGestureClick(like_x, like_y);
            }
            SystemClock.sleep(200);
            Log.i(TAG, "执行了一次点赞操作");
        }
    }

    /**
     * 检查是否为广告
     *
     * @return
     */
    private boolean CheckAdv() {
        SystemClock.sleep(200);
        List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_c);
        if (nodes.isEmpty() == false) {
            for (AccessibilityNodeInfo info : nodes) {
                if (info.getText() == null)
                    continue;
                Rect rect = new Rect();
                info.getBoundsInScreen(rect);
                if (rect.top < start_y)
                    continue;
                String text = info.getText().toString();
                Log.e(TAG, "详情" + nodes.size() + "--" + text);
                return text.endsWith("[t]") || text.endsWith("广告") || (text.contains("首付") && (text.contains("月供") || text.contains("看房")) || text.contains("@官方小助手"));
            }
        }
        return false;
    }

    /**
     * 检查是否为直播
     *
     * @return
     */
    private boolean CheckOnLone() {
        SystemClock.sleep(200);
        List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_d);
        if (nodes.isEmpty() == false) {
            return true;
        }
        return false;
    }

    private String gettext(List<AccessibilityNodeInfo> data) {
        if (data == null || data.size() == 0)
            return "";
        String text = "";
        try {
            text = data.get(0).getText().toString();
        } catch (Exception e) {
        }
        return text;
    }

    private long gettextnum(List<AccessibilityNodeInfo> data) {
        if (data == null || data.size() == 0)
            return 0l;

        double num = 0;
        try {
            String ss = data.get(0).getText().toString();
            if (ss.endsWith("w")) {
                num = Double.parseDouble(ss.replace("w", "")) * 10000;
            } else {
                num = TextUtils.isEmpty(ss) ? 0 : Double.parseDouble(ss);
            }
        } catch (Exception e) {

        }
        return (long) num;
    }

    /**
     * 精准引流
     */
    private void AccurateGuide() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null)
            return;

        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_a);
        List<AccessibilityNodeInfo> list_name = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_b);
        if (list_name == null || list_name.size() == 0) {
            isWork = false;
            return;
        }

        for (int n = 0; n < list_name.size(); n++) {
            SystemClock.sleep(200);
            AccessibilityNodeInfo info = list.get(n);
            AccessibilityNodeInfo infoname = list_name.get(n);
            String name = infoname.getText().toString();
            if (stack_task.contains(name) || info == null || info.getParent() == null)
                continue;

            info.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
            SystemClock.sleep(taskconfig.oprtime);

            stack_task.add(infoname.getText().toString());

            AccessibilityNodeInfo uerWindow = getRootInActiveWindow();
            //获取粉丝数
            long like = gettextnum(uerWindow.findAccessibilityNodeInfosByViewId(config.id_c));
            long follow = gettextnum(uerWindow.findAccessibilityNodeInfosByViewId(config.id_d));
            long fans = gettextnum(uerWindow.findAccessibilityNodeInfosByViewId(config.id_e));
            int vlog_num = 0;
            //
            List<AccessibilityNodeInfo> tabnum = uerWindow.findAccessibilityNodeInfosByViewId("android:id/text1");
            AccessibilityNodeInfo btnvlog = null;
            if (tabnum != null && tabnum.size() > 2) {
                if (tabnum.size() == 3) {
                    String str = tabnum.get(0).getText().toString().replace("作品 ", "").trim();
                    vlog_num = str.equals("") ? 0 : Integer.parseInt(str);
                    btnvlog = tabnum.get(1);
                } else {
                    //有商品列表
                    String str = tabnum.get(1).getText().toString().replace("作品 ", "").replace("作品", "").trim();
                    vlog_num = str.equals("") ? 1000 : Integer.parseInt(str);
                    btnvlog = tabnum.get(2);
                }
            }

            //返回上一级
            List<AccessibilityNodeInfo> btnback = uerWindow.findAccessibilityNodeInfosByViewId(config.id_i);
            if (like < taskconfig.like_num || follow < taskconfig.follow_num || fans < taskconfig.fans_num || vlog_num < 5 || btnvlog == null) {
                if (btnback.size() > 0) {
                    btnback.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                } else {
                    performGlobalAction(GLOBAL_ACTION_BACK);
                }
                continue;
            }

            SystemClock.sleep(100);
            btnvlog.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);

            //执行关注
            List<AccessibilityNodeInfo> follows = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_l);
            if (follows != null && follows.size() > 0) {
                AccessibilityNodeInfo btnfollow = follows.get(0);
                String str = btnfollow.getText().toString();
                if (str.equals("#  关注") || str.equals("#  回关")) {
                    btnfollow.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    showtaskmsg("关注用户:" + name);
                }
            }

            showtaskmsg("查看用户:" + name);

            SystemClock.sleep(1000);
            //查看视频
            UpLongGesture();
            SystemClock.sleep(2000);


            boolean isfind = true;//选择符合条件的内容
            int lookcount = 0;
            while (isfind) {
                if (lookcount == 10)
                    break;
                //观看视频
                int time = random.nextInt(2000, 20000);
                List<AccessibilityNodeInfo> vlog_time = uerWindow.findAccessibilityNodeInfosByViewId(config.id_f);

                boolean isltely = true;
                //三天内
                if (taskconfig.lately) {
                    if (vlog_time != null && vlog_time.size() > 0) {
                        String text = vlog_time.get(vlog_time.size() - 1).getText().toString();
                        isltely = text.contains("分钟") || text.contains("小时") || text.contains("天");
                    }
                }

                //作品点赞数
                List<AccessibilityNodeInfo> vlog_like = uerWindow.findAccessibilityNodeInfosByViewId(config.id_h);
                if (vlog_like != null && vlog_like.size() > 0) {
                    String numstr = vlog_like.get(vlog_like.size() - 1).getText().toString().replace("人赞过", "");
                    float num = TextUtils.isEmpty(numstr) ? 0 : Float.parseFloat(numstr.replace("w", ""));
                    if (numstr.contains("w"))
                        num *= 10000;
                    if (taskconfig.single_like_num > num)
                        isltely = false;
                }

                lookcount++;
                //切换下一个
                if (isltely == false) {
                    UpLongGesture();
                    SystemClock.sleep(random.nextInt(500, 2000));
                    continue;
                }

                showtaskmsg("观看视频:" + df.format(time / 1000d) + "秒");
                SystemClock.sleep(time);
                //寻找点赞按钮
                List<AccessibilityNodeInfo> btnlike = uerWindow.findAccessibilityNodeInfosByViewId(config.id_g);
                if (btnlike != null && btnlike.size() > 0) {
                    btnlike.get(btnlike.size() - 1).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    showtaskmsg("执行点赞");
                    isfind = false;
                    SystemClock.sleep(500);
                }
            }

            if (btnback.size() > 0) {
                btnback.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            } else {
                performGlobalAction(GLOBAL_ACTION_BACK);
            }
        }

        while (stack_task.size() > 30) {
            stack_task.remove(0);
        }


        //检查执行完成时间
        if (endTaskTime - System.currentTimeMillis() <= 0) {
            showtaskmsg(taskname + "执行完毕");
            isWork = false;
        }
        showtasktime();
        if (ScrollyRlyView(config.id_j) == false) {
            showtaskmsg(taskname + "执行完毕");
            isWork = false;
        }
        SystemClock.sleep(2000);
    }

    /**
     * 一键取关
     */
    private void CancelFollow(String opertext, String opertext1) {
        //名称 hr_
        //按钮 a2n
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null)
            return;

        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_a);
        List<AccessibilityNodeInfo> list_name = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_b);
        if (list == null || list.size() == 0) {
            isWork = false;
            return;
        }

        for (int n = 0; n < list.size(); n++) {
            AccessibilityNodeInfo info = list.get(n);
            AccessibilityNodeInfo infoname = list_name.get(n);

            if (info.getText().equals(opertext) == true || info.getText().equals(opertext1) == true) {
                showtaskmsg("取消关注:" + infoname.getText());

                info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                opercount++;
                SystemClock.sleep(200);
                if (needcount == opercount) {
                    isWork = false;
                    break;
                }
            }
        }

        isWork = ScrollyRlyView(config.id_c);
        SystemClock.sleep(500);
    }

    /**
     * 自动广告
     */
    private void AutoAdvertiseme(boolean sayhello, boolean sendmsg, boolean sendimg) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null)
            return;

        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_a);
//        List<AccessibilityNodeInfo> list_name = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_b);
        if (list != null && list.size() > 0) {

            List<AccessibilityNodeInfo> list_name = new ArrayList<>();
            for (int n = 0; n < list.size(); n++) {
                AccessibilityNodeInfo info = list.get(n);
                AccessibilityNodeInfo infoname = null;
                if (info.getChildCount() > 2) {
                    infoname = info.getChild(1);
                    AccessibilityNodeInfo flag = info.getChild(2);
                    if (infoname == null || (flag != null && flag.getText().toString().equals("官方")))
                        continue;
                } else {
                    continue;
                }
                //AccessibilityNodeInfo infoname = list_name.get(n);
                String name = infoname.getText().toString();
                if (name.equals("抖音小助手") || name.equals("粉丝") || name.equals("评论和@") || name.equals("赞") || name.equals("求更新") || name.equals("陌生人消息")) {
                    continue;
                }

                list_name.add(infoname);
            }


            for (int n = 0; n < list_name.size(); n++) {
                AccessibilityNodeInfo infoname = list_name.get(n);
                String name = infoname.getText().toString();
                if (stack_task.contains(name)) {
                    continue;
                }

                //任务完成跳出循环
                if (needcount == opercount || isWork == false) {
                    break;
                }

                showtaskmsg("自动广告:" + name);


                if (infoname.performAction(AccessibilityNodeInfo.ACTION_CLICK) == false) {
                    if (OnViewClick(infoname) == false)
                        continue;
                }

                stack_task.add(infoname.getText().toString());

                SystemClock.sleep(taskconfig.oprtime);
                AccessibilityNodeInfo msgwindow = getRootInActiveWindow();
                if (msgwindow == null) {
                    SystemClock.sleep(taskconfig.oprtime);
                    msgwindow = getRootInActiveWindow();
                    if (msgwindow == null) {
                        if (isChtRoom)
                            performGlobalAction(GLOBAL_ACTION_BACK);
                        continue;
                    }
                }

                boolean isexec = false;
                if (isChtRoom == true) {
                    if (sayhello) {
                        //发送表情
                        List<AccessibilityNodeInfo> emotist = msgwindow.findAccessibilityNodeInfosByViewId(config.id_c);
                        if (emotist != null && emotist.size() > 0) {
                            emotist.get(random.nextInt(0, emotist.size() - 1)).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            SystemClock.sleep(taskconfig.oprtime);
                            isexec = true;
                        }
                    }

                    if (sendmsg && TextUtils.isEmpty(taskconfig.msg) == false && CheckSendMsg("text", name, taskconfig.msg) == false) {
                        //自定义文字广告
                        List<AccessibilityNodeInfo> list_edit = msgwindow.findAccessibilityNodeInfosByViewId(config.id_d);
                        if (list_edit != null && list_edit.size() > 0) {
                            AccessibilityNodeInfo edit = list_edit.get(0);
                            Bundle arguments = new Bundle();
                            arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, taskconfig.msg);
                            edit.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
                            SystemClock.sleep(taskconfig.oprtime);
                        }

                        //提交按钮 com.ss.android.ugc.aweme:id/flu
                        List<AccessibilityNodeInfo> list_btn = msgwindow.findAccessibilityNodeInfosByViewId(config.id_e);
                        if (list_btn != null && list_btn.size() > 0) {
                            AccessibilityNodeInfo btn = list_btn.get(0);
                            btn.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                            //记录文字
                            AddAutoLog("text", name, taskconfig.msg);

                            SystemClock.sleep(taskconfig.oprtime);
                            isexec = true;
                        }
                    }

                    //发送收藏的图片
                    if (sendimg && CheckSendMsg("fav_img", name, "img:" + taskconfig.like_num) == false) {
                        List<AccessibilityNodeInfo> list_emot = msgwindow.findAccessibilityNodeInfosByViewId(config.id_f);
                        if (list_emot != null && list_emot.size() > 0) {
                            AccessibilityNodeInfo btn = list_emot.get(0);

                            OnViewClick(btn);
                            SystemClock.sleep(taskconfig.oprtime);
                        }

                        //选择我的表情
                        List<AccessibilityNodeInfo> list_my = msgwindow.findAccessibilityNodeInfosByViewId(config.id_g);
                        Log.e(TAG, list_my == null ? "表情包" : list_my.toString());
                        if (list_my != null && list_my.size() > 0) {
                            AccessibilityNodeInfo btn = list_my.get(1);
                            btn.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            SystemClock.sleep(taskconfig.oprtime);
                        }

                        List<AccessibilityNodeInfo> emotist = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_h);
                        Log.e(TAG, emotist == null ? "个数0" : emotist.toString());
                        if (emotist != null && emotist.size() > 1) {
                            for (int m = 0; m < emotist.size(); m++) {
                                AccessibilityNodeInfo eicno = emotist.get(m);//默认推荐的视频是不存在的
                                if (TextUtils.isEmpty(eicno.getContentDescription()) || eicno.getContentDescription().equals("自定义表情") == false)
                                    continue;

                                //判断是否在
                                if (m <= emotist.size()) {
                                    AccessibilityNodeInfo myfav = emotist.get(m + taskconfig.like_num);//我的表情

                                    Log.e(TAG, "表情包：" + myfav.toString());
                                    //记录文字
                                    AddAutoLog("fav_img", name, "img:" + taskconfig.like_num);
                                    if (BuildConfig.DEBUG == false) {
                                        OnViewClick(emotist.get(m + taskconfig.like_num));
                                        SystemClock.sleep(taskconfig.oprtime);
                                    }
                                    break;
                                }
                                isexec = true;
                            }
                        }
                    }

                    if (isexec == true) {
                        opercount++;
                    }
                    //返回上一页
                    List<AccessibilityNodeInfo> listback = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_i);
                    if (listback != null && listback.size() > 0) {
                        listback.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);//返回上一页
                        SystemClock.sleep(taskconfig.oprtime * 2);
                    }
                }
//            else
//            {
//                performGlobalAction(GLOBAL_ACTION_BACK);
//            }
            }
        }
        while (stack_task.size() > 30)
            stack_task.remove(0);

        //上滑数据
//        UpGesture();

        if (ScrollyRlyView(config.id_j) == false) {
            showtaskmsg("自动广告:滑到底部");
            isWork = false;

        }
        SystemClock.sleep(taskconfig.oprtime);
    }

    /**
     * 一键识别
     */
    private void Recognition() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null)
            return;
        //识别官方的自动不点击进去
        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_a);
        if (list != null && list.size() > 0) {
            List<AccessibilityNodeInfo> list_name = new ArrayList<>();
            List<AccessibilityNodeInfo> list_head = new ArrayList<>();//头像
            for (int n = 0; n < list.size(); n++) {
                AccessibilityNodeInfo info = list.get(n);
                AccessibilityNodeInfo infoname = null;
                if (info.getChildCount() > 2) {
                    infoname = info.getChild(1);
                    AccessibilityNodeInfo flag = info.getChild(2);
                    if (infoname == null || (flag != null && flag.getText().toString().equals("官方")))
                        continue;
                } else {
                    continue;
                }
                //AccessibilityNodeInfo infoname = list_name.get(n);
                String name = infoname.getText().toString();
                if (name.equals("抖音小助手") || name.equals("粉丝") || name.equals("评论和@") || name.equals("赞") || name.equals("求更新") || name.equals("陌生人消息") || stack_task.contains(name)) {
                    continue;
                }

                list_head.add(info.getChild(0));
                list_name.add(infoname);
            }

            for (int n = 0; n < list_name.size(); n++) {
                AccessibilityNodeInfo infoname = list_name.get(n);
                String name = infoname.getText().toString();

                if (stack_task.contains(name))
                    continue;

                //任务完成跳出循环
                if (needcount == opercount || isWork == false) {
                    break;
                }

                opercount++;

                showtaskmsg("一键识别:" + name);
                //点击头像
                AccessibilityNodeInfo head = list_head.get(n);

                int clickcount = 0;
                if ((head.performAction(AccessibilityNodeInfo.ACTION_CLICK) == false && clickcount < 3)) {
                    SystemClock.sleep(500);
                    if (OnViewClick(head) == false)
                        continue;
                }

                stack_task.add(infoname.getText().toString());

                AccessibilityNodeInfo uerWindow = getRootInActiveWindow();
                //获取粉丝数
                long like = gettextnum(uerWindow.findAccessibilityNodeInfosByViewId(config.id_c));
                long follow = gettextnum(uerWindow.findAccessibilityNodeInfosByViewId(config.id_d));
                long fans = gettextnum(uerWindow.findAccessibilityNodeInfosByViewId(config.id_e));
                int vlog_num = 0;
                //
                List<AccessibilityNodeInfo> tabnum = uerWindow.findAccessibilityNodeInfosByViewId("android:id/text1");
                if (tabnum != null && tabnum.size() > 2) {
                    try {
                        if (tabnum.size() == 3) {
                            String str = tabnum.get(0).getText().toString().replace("作品 ", "").trim();
                            vlog_num = str.equals("") ? 0 : Integer.parseInt(str);
                        } else {
                            //有商品列表
                            String str = tabnum.get(1).getText().toString().replace("作品 ", "").replace("作品", "").trim();
                            vlog_num = str.equals("") ? 1000 : Integer.parseInt(str);
                        }
                    } catch (NumberFormatException e) {

                    }
                }

                SystemClock.sleep(500);

                //关注大于  粉丝大于  作品少于
                if (follow > taskconfig.follow_num || fans > taskconfig.fans_num || vlog_num < taskconfig.vlog_num) {
                    //点击取消关注
                    if (taskconfig.auto_follow == true) {
                        List<AccessibilityNodeInfo> nofollows = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_g);
                        if (nofollows != null && nofollows.size() > 0) {
                            AccessibilityNodeInfo nofollow = nofollows.get(0);
                            String str = nofollow.getText().toString();
                            if (str.contains("取消关注")) {
                                nofollow.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            }

                            if (str.contains("互相关注")) {
                                nofollow.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                DialogOnClick(BuildConfig.DEBUG ? config.id_p : config.id_o);
                            }
                        }
                    }

                    //点击拉黑
                    if (taskconfig.auto_like == true) {
                        List<AccessibilityNodeInfo> momores = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_l);
                        if (momores != null && momores.size() > 0) {
                            momores.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            SystemClock.sleep(200);
                            //获取拉黑按钮
                            List<AccessibilityNodeInfo> btn_dels = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_m);//
                            if (btn_dels != null && btn_dels.size() > 0) {
                                btn_dels.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                SystemClock.sleep(200);
                                //确认删除
                                DialogOnClick(BuildConfig.DEBUG ? config.id_p : config.id_o);

                            }
                        }
                    }
                }
                //返回上一级
                List<AccessibilityNodeInfo> btnback = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_i);
                //返回上一页
                if (btnback.size() > 0) {
//                    btnback.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    while (btnback.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK) == false) {
                        SystemClock.sleep(500);
                    }
                } else {
                    performGlobalAction(GLOBAL_ACTION_BACK);
                }
                SystemClock.sleep(500);
            }
        }

        while (stack_task.size() > 30)
            stack_task.remove(0);

        if (ScrollyRlyView(config.id_j) == false) {
            showtaskmsg("一键识别:滑到底部");
            isWork = false;

        }
        SystemClock.sleep(1000);
    }

    /**
     * 自动广告
     */
    private void AutoReadMessage() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null)
            return;

        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_a);
        //List<AccessibilityNodeInfo> list_name = nodeInfo.findAccessibilityNodeInfosByViewId(config.id_b);
        if (list != null && list.size() > 0) {
            List<AccessibilityNodeInfo> list_name = new ArrayList<>();
            for (int n = 0; n < list.size(); n++) {
                AccessibilityNodeInfo info = list.get(n);
                AccessibilityNodeInfo infoname = null;
                if (info.getChildCount() > 4) {
                    infoname = info.getChild(1);
                    AccessibilityNodeInfo flag = info.getChild(2);
                    if (infoname == null || (flag != null && flag.getText().toString().equals("官方")))
                        continue;
                } else {
                    continue;
                }
                //AccessibilityNodeInfo infoname = list_name.get(n);
                String name = infoname.getText().toString();
                if (name.equals("抖音小助手") || name.equals("粉丝") || name.equals("评论和@") || name.equals("赞") || name.equals("求更新") || name.equals("陌生人消息") || stack_task.contains(name)) {
                    continue;
                }

                list_name.add(infoname);
            }

            for (int n = 0; n < list_name.size(); n++) {  //任务完成跳出循环
                if (isWork == false) {
                    break;
                }
                AccessibilityNodeInfo infoname = list_name.get(n);
                String name = infoname.getText().toString();
                showtaskmsg("读取消息:" + name);

                if (infoname.performAction(AccessibilityNodeInfo.ACTION_CLICK) == false) {
                    if (OnViewClick(infoname) == false)
                        continue;
                }

                stack_task.add(infoname.getText().toString());

                SystemClock.sleep(taskconfig.oprtime);
                AccessibilityNodeInfo msgwindow = getRootInActiveWindow();
                if (msgwindow == null) {
                    SystemClock.sleep(taskconfig.oprtime);
                    msgwindow = getRootInActiveWindow();
                    if (msgwindow == null) {
                        if (isChtRoom)
                            performGlobalAction(GLOBAL_ACTION_BACK);
                        continue;
                    }
                }

                if (isChtRoom == true) {
                    //返回上一页
                    List<AccessibilityNodeInfo> listback = msgwindow.findAccessibilityNodeInfosByViewId(config.id_i);
                    if (listback != null && listback.size() > 0) {
                        listback.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);//返回上一页
                        SystemClock.sleep(taskconfig.oprtime * 2);
                    } else {
                        performGlobalAction(GLOBAL_ACTION_BACK);
                    }
                }
            }
        }
        while (stack_task.size() > 30)
            stack_task.remove(0);

        if (ScrollyRlyView(config.id_j) == false) {
            showtaskmsg("自动广告:滑到底部");
            isWork = false;
        }
        SystemClock.sleep(taskconfig.oprtime);
    }


    private void DialogOnClick(String id) {
        SystemClock.sleep(500);
        //确认删除
        List<AccessibilityNodeInfo> btn_ok = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(id);
        if (btn_ok != null && btn_ok.size() > 0) {
            btn_ok.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            SystemClock.sleep(500);
        }
    }


    /**
     * 向下滑动 recycleview
     *
     * @param res_id
     */
    private boolean ScrollyRlyView(String res_id) {
        List<AccessibilityNodeInfo> infos = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(res_id);
        if (infos != null && infos.size() > 0) {
            AccessibilityNodeInfo lv = infos.get(0);
            return lv.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        }
        return true;
    }

    /**
     * 操作日记
     *
     * @param type
     * @param reviceman
     * @param content
     */
    private void AddAutoLog(String type, String reviceman, String content) {
        if (DBAccess != null) {
            String sql = String.format("INSERT INTO hy_auto_adv_log (guid,reviceman,sendtype,sendmsg,createdate) VALUES ('%s','%s','%s','%s','%s')", UUID.randomUUID().toString(), reviceman, type, content, DateUtils.DateTimeNow());

            if (DBAccess.Execute(sql)) {
                Log.e(TAG, "数据保存成功");
            } else {
                Log.e(TAG, "数据保存失败");
            }
        }
    }

    /**
     * 检查是否重复发送消息
     *
     * @param type
     * @param reviceman
     * @param content
     * @return
     */
    private boolean CheckSendMsg(String type, String reviceman, String content) {
        String sql = String.format("select COUNT(1) from hy_auto_adv_log where reviceman='%s' and sendtype='%s' and sendmsg='%s'", reviceman, type, content);
        if (DBAccess != null) {
            Cursor cursor = DBAccess.Query(sql);
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getInt(0) > 0;
            }
        }
        return false;
    }


    private boolean OnViewClick(AccessibilityNodeInfo info) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Rect rect = new Rect();
            info.getBoundsInScreen(rect);

            int x = (rect.right + (rect.left - rect.right) / 2);//去重复检查
            int y = (rect.bottom + (rect.top - rect.bottom) / 2);//去重复检查

            //首页底部有按钮
            if (isMain == true && y > Max_y)
                return false;

            dispatchGestureClick(x, y);

        }
        return true;
    }

    WindowManager windowManager;
    private View floatview;
    private TextView labhead;
    private ImageView iv_start;
    private ImageView iv_close;
    private ListView lv;
    private ArrayAdapter<String> adapter;
    //执行的任务
    private ArrayList<String> mTask = new ArrayList<>();

    private void showFloatingWindow() {
        // 新建悬浮窗控件
        floatview = LayoutInflater.from(this).inflate(R.layout.layout_window_task, null);
        labhead = floatview.findViewById(R.id.labhead);
        iv_start = floatview.findViewById(R.id.iv_start);
        iv_close = floatview.findViewById(R.id.iv_close);
        lv = floatview.findViewById(R.id.lv);

        //显示类型
        labhead.setText(taskname + ":" + taskconfig.runtime + taskconfig.unit + "\r\n设备:" + Build.MODEL);

        iv_start.setOnClickListener(listener);
        iv_close.setOnClickListener(listener);

        adapter = new ArrayAdapter<>(this, R.layout.layout_task_item, mTask);
        lv.setAdapter(adapter);

        //默认显示位置 一开始 以屏幕中间
        AddView(floatview, (int) (ConstValues.Screen_Width / 3.5), ConstValues.Screen_Height / 5, -ConstValues.Screen_Width, -ConstValues.Screen_Height / 3);

        iv_start.setImageResource(isWork ? R.drawable.pause : R.drawable.start);
    }


    void AddView(View view, int w, int h, int x, int y) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) {
            // 获取WindowManager服务
            windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            // 设置LayoutParam
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            layoutParams.format = PixelFormat.RGBA_8888;
            layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            //宽高自适应
            layoutParams.width = w;
            layoutParams.height = h;
            //显示的位置
            layoutParams.x = x;
            layoutParams.y = y;

            // 新建悬浮窗控件
            view.setOnTouchListener(new FloatingOnTouchListener(layoutParams));
            // 将悬浮窗控件添加到WindowManager
            windowManager.addView(view, layoutParams);
        }
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == iv_start) {
                isWork = isWork == true ? false : true;
                iv_start.setImageResource(isWork ? R.drawable.pause : R.drawable.start);

                if (isWork == false) {
                    if (workThread != null) {
                        workThread.interrupt();
                        workThread = null;
                        SystemClock.sleep(100);
                    }
                } else {
                    if (startTaskTime == 0) {
                        startTaskTime = System.currentTimeMillis();//开始时间
                        endTaskTime = System.currentTimeMillis() + taskconfig.runtime * 3600 * 1000;//结束时间
                    }

                    execTask();
                }

            } else {
                if (workThread != null) {
                    workThread.interrupt();
                    workThread = null;
                    SystemClock.sleep(200);
                }
                isWork = false;
                windowManager.removeView(floatview);
            }
        }
    };


    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;
        WindowManager.LayoutParams layoutParams;

        public FloatingOnTouchListener(WindowManager.LayoutParams lp) {
            layoutParams = lp;
        }


        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;
                    // 更新悬浮窗控件布局
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }

    }

    /**
     * 获取按钮的位置
     */
    private void getbtnconfig() {

        DYConfig config = DYVersionUtils.getTypeConfig(1, ConstValues.getDyAPPVer(this));
        like_x = ConstValues.getIntValue(this, "like_x", 0);
        like_y = ConstValues.getIntValue(this, "like_y", 0);
        follow_x = ConstValues.getIntValue(this, "follow_x", 0);
        follow_y = ConstValues.getIntValue(this, "follow_y", 0);

        if (like_x > 0 && like_y > 0 && follow_x > 0 && follow_y > 0)
            return;

        boolean isfind = true;
        int h = ConstValues.Screen_Height / 4;
        while (isfind) {


            List<AccessibilityNodeInfo> list = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_b);
            //获取关注按钮
            if (list.isEmpty() == false) {
                for (AccessibilityNodeInfo info : list) {
                    Rect rect = new Rect();
                    info.getBoundsInScreen(rect);
                    if (rect.top > h && rect.top < ConstValues.Screen_Height) {
                        like_x = rect.right + (rect.left - rect.right) / 2;
                        like_y = rect.bottom + (rect.top - rect.bottom) / 2;
                        break;
                    }
                }

                //获取关注按钮
                List<AccessibilityNodeInfo> guanzhuList = getRootInActiveWindow().findAccessibilityNodeInfosByViewId(config.id_a);
                if (guanzhuList.isEmpty() == false) {
                    for (AccessibilityNodeInfo info : guanzhuList) {
                        Rect rect = new Rect();
                        info.getBoundsInScreen(rect);
                        if (rect.top > h && rect.top < ConstValues.Screen_Height) {
                            follow_x = rect.right + (rect.left - rect.right) / 2;
                            follow_y = rect.bottom + (rect.top - rect.bottom) / 2;
                            break;
                        }
                    }
                }
            }

            if (like_x > 0 && like_y > 0 && follow_x > 0 && follow_y > 0) {
                //缓存本地
                ConstValues.SaveValue(this, "like_x", like_x);
                ConstValues.SaveValue(this, "like_y", like_y);
                ConstValues.SaveValue(this, "follow_x", follow_x);
                ConstValues.SaveValue(this, "follow_y", follow_y);

                Toast.makeText(getApplicationContext(), "按钮内容采集完成", Toast.LENGTH_LONG).show();
                isfind = false;
            }
            //切换视频
            UpGesture();
            SystemClock.sleep(5000);
        }
    }

}
